class Login {
    returnUrl = ''
    constructor() {
        //设置登陆成功后的会跳地址
        let param = location.search;
        if (param) {
            param = param.split('=')[1];
            this.returnUrl = param;
        }

        //登录按钮绑定事件
        this.$('.over').addEventListener('click', this.checkLogin)
    }
    //验证登录数据
    checkLogin = () => {
        //获取表单数据
        let form = document.forms.login.elements;
        let username = form.uname.value.trim();
        let password = form.password.value.trim();
        //非空验证
        // if (!username || !password) {
        //     alert('不能为空');
        //     return;
        // }
        if (!username) {
            // alert('不能为空');
            layer.tips('用户名不能为空', form.uname);
            return;
        }
        if (!password) {
            // alert('不能为空');
            layer.tips('密码不能为空', form.password);
            return;
        }
        // 设置编码方式
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        //发送ajax登录
        let param = `username=${username}&password=${password}`
        axios.post('http://localhost:8888/users/login', param)
            .then(({ status, data }) => {
                // console.log(data, status);
                //判断是否登陆成功
                if (status != 200 || data.code != 1) {
                    // alert('登陆失败');
                    layer.msg('登陆失败..')
                    return;
                }
                //将token   进行存储
                localStorage.setItem('token', data.token);
                //存入用户id
                localStorage.setItem('user_id', data.user.id)

                //回调到原来页面
                //returnUrl为空返回list，有值则跳转到指定页面
                this.returnUrl ? location.assign(this.returnUrl) : location.assign
                    ('./index.html');
            });
        this.saveId(username);
    }
    saveId(username) {
        localStorage.setItem('userName', username)
    }

    //获取节点的方法
    $(ele) {
        let res = document.querySelectorAll(ele);
        return res.length == 1 ? res[0] : res;
    }
}
new Login;